package org.bite.utils;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//封装 连接 释放操作
public class DBUtil {
    //创建数据源并获取数据库连接

    //数据源
    private static DataSource dataSource=null;
    //数据库连接串
    private static final String URL="jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8" +
            "&allowPublicKeyRetrieval=true&useSSL=false";
    //用户名
    private static final String USER="root";
    //密码
    private static final String PASSWORD="123456";

    //当类加载到JVM时,就执行数据源的初始化
    static {
        MysqlDataSource mysqlDataSource=new MysqlDataSource();
        mysqlDataSource.setURL(URL);
        mysqlDataSource.setUser(USER);
        mysqlDataSource.setPassword(PASSWORD);
        dataSource=mysqlDataSource;
    }

    private DBUtil(){};//构造方法私有化 防止new 对象
    //创建连接对象

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public static void close(ResultSet resultSet, Statement statement,Connection connection){
        if (resultSet == null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        //释放Statement
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        //关闭数据库连接
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
